/*
 * Author: JacksonCoder
 * FileName: ScheduledThreadPoolTimeoutExample
 * Version: 1.0.0
 * Date: 2025/2/24
 */

import java.util.concurrent.*;

public class ScheduledThreadPoolTimeoutExample {

    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);

        Callable<String> task = new Callable<String>() {

            @Override
            public String call() throws Exception {
                Thread.sleep(10000); // 模拟任务运行时间
                return "Task completed";
            }
        };

        // 提交任务并返回Future
        Future<String> future = executor.submit(task);

        // 设置超时时间为1秒
        executor.schedule(() -> {
            if (!future.isDone()) {
                System.out.println("Task timed out");
                future.cancel(true); // 取消任务
            }
        }, 1, TimeUnit.SECONDS); // 超时时间为1秒

        try {
            String result = future.get(); // 获取任务结果
            System.out.println(result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }


    }

}
